<template>
  <a-spin :spinning="confirmLoading">
    <j-form-container :disabled="formDisabled">
      <a-form :form="form" slot="detail">
        <a-row>
          <a-col :span="24">
            <a-form-item label="选择一个商品" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <j-search-select-tag
                placeholder="请选择一个商品"
                v-decorator="['commodityId', validatorRules.commodityId]"
                :dictOptions="commodityList"
                @change="changeCommodity">
              </j-search-select-tag>
            </a-form-item>
          </a-col>
          <!--<a-col :span="24">
            <a-form-item label="批次号" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input v-decorator="['batchNo', validatorRules.batchNo]" placeholder="请输入批次号"  ></a-input>
            </a-form-item>
          </a-col>-->
          <a-col :span="24">
            <a-form-item label="制码数量" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input-number :max="100000" v-decorator="['codeNum', validatorRules.codeNum]"  placeholder="请输入制码数量" :disabled="isDisabled" style="width: 100%"  />
            </a-form-item>
          </a-col>
          <a-col :span="24">
            <a-span style="color: #ff0000;margin-left: 20%">{{codeMessage}}</a-span>
          </a-col>
         <!-- <a-col v-if="showFlowSubmitButton" :span="24" style="text-align: center">
            <a-button @click="submitForm">提 交</a-button>
          </a-col>-->
        </a-row>
      </a-form>
    </j-form-container>
  </a-spin>
</template>

<script>

  import { httpAction, getAction } from '@/api/manage'
  import pick from 'lodash.pick'
  import { validateDuplicateValue } from '@/utils/util'

  export default {
    name: 'QySourceCodeCreateForm',
    components: {
    },
    props: {
      //流程表单data
      formData: {
        type: Object,
        default: ()=>{},
        required: false
      },
      //表单模式：true流程表单 false普通表单
      formBpm: {
        type: Boolean,
        default: false,
        required: false
      },
      //表单禁用
      disabled: {
        type: Boolean,
        default: false,
        required: false
      }
    },
    data () {
      return {
        form: this.$form.createForm(this),
        model: {},
        labelCol: {
          xs: { span: 24 },
          sm: { span: 5 },
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 16 },
        },
        confirmLoading: false,
        validatorRules: {
          commodityId: {
            rules: [
              { required: true, message: '请选择一个商品!'},
            ]
          }/*,
          batchNo: {
            rules: [
              { required: true, message: '请输入批次号!'},
              {validator:this.checkBatchNo}
            ]
          }*/,
          codeNum: {
            rules: [
              { required: true, message: '请输入制码数量!'},
              { pattern: /^-?\d+$/, message: '请输入整数!'},
            ]
          },
        },
        url: {
          add: "/qy/qySourceCodeCreate/add",
          edit: "/qy/qySourceCodeCreate/edit",
          queryById: "/qy/qySourceCodeCreate/queryById"
        },
        commodityList:[],
        codeMessage:"",
        commodityMap:{},
        isDisabled:false
      }
    },
    computed: {
      formDisabled(){
        if(this.formBpm===true){
          if(this.formData.disabled===false){
            return false
          }
          return true
        }
        return this.disabled
      },
      showFlowSubmitButton(){
        if(this.formBpm===true){
          if(this.formData.disabled===false){
            return true
          }
        }
        return false
      }
    },
    created () {
      //如果是流程中表单，则需要加载流程表单data
      this.showFlowData();
      this.loadCommodity();
    },
    methods: {
      add () {
        this.codeMessage = "";
        this.edit({});
      },
      edit (record) {
        this.form.resetFields();
        this.model = Object.assign({}, record);
        this.visible = true;
        this.$nextTick(() => {
          this.form.setFieldsValue(pick(this.model,'updateTime','commodityId','batchNo','codeNum'))
        })
      },
      //渲染流程表单数据
      showFlowData(){
        if(this.formBpm === true){
          let params = {id:this.formData.dataId};
          getAction(this.url.queryById,params).then((res)=>{
            if(res.success){
              this.edit (res.result);
            }
          });
        }
      },
      submitForm () {
        const that = this;
        // 触发表单验证
        this.form.validateFields((err, values) => {
          console.log(values)
          if (!err) {
            that.confirmLoading = true;
            let httpurl = this.url.add;
            let  method = 'post';

            let formData = Object.assign(this.model, values);
            httpAction(httpurl,formData,method).then((res)=>{
              if(res.success){
                that.$message.success(res.message);
                that.$emit('ok');
              }else{
                that.$message.warning(res.message);
              }
            }).finally(() => {
              that.confirmLoading = false;
            })
          }
         
        })
      },
      popupCallback(row){
        this.form.setFieldsValue(pick(row,'updateTime','commodityId','batchNo','codeNum'))
      },loadCommodity(){
        var that =this;
        httpAction("/qy/qyCommodity/findCommodityList",{},"GET").then((res)=>{
          if(res.success){
            if(res.result){
              for(var k in res.result){
                that.commodityList.push({
                  text:res.result[k].commodityName,
                  value:res.result[k].id
                });
                that.commodityMap[res.result[k].id] = res.result[k];
              }
            }
          }
        })
      },checkBatchNo(rule, value, callback){
        const form = this.form;
        var reg = new RegExp("[\\u4E00-\\u9FFF]+","g");
        if(form.getFieldValue('batchNo').length<6||form.getFieldValue('batchNo').length>16){
          callback('批次号为6-16由字母、符号、数字组成！');
        }else if(reg.test(form.getFieldValue('batchNo'))){
          callback('批次号不能输入汉字！');
        }else{
          callback();
        }
      },changeCommodity(val){
        let commodity = this.commodityMap[val];
          if(commodity){
             if(commodity.commodityType==1){
               //一物一码
               this.codeMessage ="该商品可用余额："+commodity.oneCodeNum+"个";
               this.model.codeNum = undefined;
               this.isDisabled = false;
             }else{
               //N物一码
               this.codeMessage ="该商品溯源类型为N物1码，每次支持生成一个码";
               this.model.codeNum = 1;
               this.isDisabled = true;
             }
            this.$nextTick(() => {
              this.form.setFieldsValue(pick(this.model, 'updateTime', 'commodityId', 'batchNo', 'codeNum'));
            });
          }
      }
    }
  }
</script>